package lingou.homework.postbar.controller.proto;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.LongNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import lingou.homework.postbar.controller.tool.JsonHelper;
import lingou.homework.postbar.domain.Message;
import lingou.homework.postbar.domain.Post;
import lingou.homework.postbar.domain.User;
import lingou.homework.postbar.exception.SystemException;
import lingou.homework.postbar.service.PostService;
import lingou.homework.postbar.service.UserService;
import lingou.homework.postbar.service.enums.MessageOpEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MessageView {
    @Autowired
    JsonMapper jsonMapper;
    @Autowired
    UserService userService;
    @Autowired
    PostService postService;

    public JsonNode expand(Message message) {
        Post post = postService.getPost(message.getPostId());
        User user = userService.getUser(post.getUserId());
        ObjectNode ret = new ObjectNode(new JsonNodeFactory(false));
        ObjectMapper objectMapper = new ObjectMapper();
        ret.set("messageId", LongNode.valueOf(message.getMessageId()));
        ret.set("post", objectMapper.valueToTree(post));
        ret.set("msgOp", LongNode.valueOf(message.getMsgOp()));
        ret.set("status", LongNode.valueOf(message.getStatus()));
        switch (MessageOpEnum.select(message.getMsgOp())) {
            case LIKE -> {
                ret.set("likes", LongNode.valueOf(message.getValue()));
                ret.set("topPostId", LongNode.valueOf(postService.getTopPost(post.getPostId()).getPostId()));
            }
            case REPLY -> {
                ret.set("user", objectMapper.valueToTree(user));
                Post fatherPost = postService.getFatherPost(message.getPostId());
                ret.set("topPostId", LongNode.valueOf(postService.getTopPost(post.getPostId()).getPostId()));
                ret.set("fatherPost", objectMapper.valueToTree(fatherPost));
            }
            case ASK -> {
                ret.set("user", objectMapper.valueToTree(user));
            }
            case NOTICE -> {}
            case DELETE -> {
                throw SystemException.UNSUPPORTED;
            }
        }
        return ret;
//        ObjectNode node = JsonHelper.fill(message, jsonMapper.getMapper("postId"));
//        node.set("message", TextNode.valueOf(MessageOpEnum.select(message.getMsgOp()).genMessage(
//                userService.getUser(message.getUserId()),
//                postService.getPost(message.getPostId()),
//                postService)));
    }
}
